//
// Created by fanghr on 17-12-25.
//

#include "server.h"
#include "test_socket.h"

server::server(boost::asio::io_service &io_service, short port) :
        io_service_(io_service),
        acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) {
    BOOST_LOG_TRIVIAL(info) << "Server start at:"
                            << boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port).address().to_string()
                            << ":"
                            << port;
    start_accept();
}

void server::start_accept() {
    session *new_session = new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
                           boost::bind(&server::handle_accept, this, new_session,
                                       boost::asio::placeholders::error));
}

uint32_t cb(boost::asio::streambuf &buf){
    boost::archive::binary_iarchive ia(buf);

    delete &ia;
    buf.consume(buf.size());
    boost::archive::binary_oarchive oa(buf);

    return (uint32_t)buf.size();
}

void server::handle_accept(session *new_session, const boost::system::error_code &error) {
    if (!error) {
        new_session->set_callback(cb);
        new_session->start();
    } else {
        delete new_session;
    }
    start_accept();
}


